#! /usr/bin/python
from flask import Flask
from flask import request
from flask import redirect
import signal
import sys
import os
import copy

cfg = os.path.join(os.path.dirname(__file__),
                   '..', 'cfg', 'at', 'other.cfg')
execfile(cfg)

app = Flask(__name__)
data = {
    'ppp_test_time': 0,
    'ppp_test_suc': 0,
    'ppp_test_fail': 0,
    'ppp_ping_time': 0,
    'ppp_ping_suc': 0,
    'ppp_ping_fail': 0,
    'ppp_unknow_host': 0,
    'rndis_test_time': 0,
    'rndis_test_suc': 0,
    'rndis_test_fail': 0,
    'rndis_ping_time': 0,
    'rndis_ping_suc': 0,
    'rndis_ping_fail': 0,
    'rndis_unknow_host': 0,
    'cmux_test_time': 0,
    'cmux_test_suc': 0,
    'cmux_test_fail': 0,
    'cmux_ping_time': 0,
    'cmux_ping_suc': 0,
    'cmux_ping_fail': 0,
    'cmux_unknow_host': 0
}

failed_list = []

test_history = []


def _list(at, ping):
    result = ""
    for i in at:
        result += i + '<br/>'
    result += '---------------------------------------' + '<br/>'
    for key in sorted(ping.keys()):
        line = key + ": " + str(ping[key]) + '<br/>'
        result += line
    return result


@app.route('/')
def index():
    ret = ''
    ret += '<h6>' + 'test times: ' + \
        str(len(test_history)) + '</h6>' + '<br/>'
    ret += _list(failed_list, data)
    return ret


@app.route('/test/<path:value>')
def ppp_rndis_cmux(value):
    count = request.args.get('count')
    key = value.split('/')
    key = '_'.join(key)
    data[key] = data[key] + int(count)
    return ('', 204)


@app.route('/at', methods=('post',))
def at():
    msg = request.form['msg']
    failed_list.append(msg)
    return ('', 204)


@app.route('/clean')
def clean():
    global failed_list
    global test_history
    test_history = []
    failed_list = []
    for key in data:
        data[key] = 0
    return redirect('/')


@app.route('/new')
def new():
    global failed_list
    global data
    global test_history
    data_copy = copy.deepcopy(data)
    failed_list_copy = copy.deepcopy(failed_list)
    test_history.append(copy.deepcopy([failed_list_copy, data_copy]))
    failed_list = []
    for key in data:
        data[key] = 0
    return ('', 204)


@app.route('/list')
def list_history():
    i = 0
    ret = ''
    for at, ping in test_history:
        if i == 0:
            i = i + 1
            continue
        ret += '<h6>' + 'time ' + str(i) + '</h6>'
        ret += _list(at, ping)
        i = i + 1
    return ret


def term_handler(signo, frame):
    sys.exit(0)


if __name__ == '__main__':
    signal.signal(signal.SIGTERM, term_handler)
    app.run(host='0.0.0.0', port=server_port)
